package de.pass.ch.datastr;

public class IntArrayGrowable {

	private int[][] data;

	private int offsetI, offsetJ;

	private int numElements;

	private final int chunkSize;

	public IntArrayGrowable(int chunkSize) {
		this.chunkSize = chunkSize;
		data = new int[1][chunkSize];
		offsetI = 0;
		offsetJ = 0;
		numElements = 0;
	}

	public void add(int val) {
		if (offsetJ == chunkSize) {
			if (data.length <= offsetI + 1)
				addChunk();
			offsetI++;
			offsetJ = 0;
		}
		data[offsetI][offsetJ++] = val;
		numElements++;
	}

	public int get(int idx) {
		int i = idx / chunkSize;
		int j = idx % chunkSize;
		return data[i][j];
	}

	public void set(int idx, int val) {
		int i = idx / chunkSize;
		int j = idx % chunkSize;
		data[i][j] = val;
	}

	public void swap(int idx1, int idx2) {
		int tmp = get(idx1);
		set(idx1, get(idx2));
		set(idx2, tmp);
	}

	public int size() {
		return numElements;
	}

	public void pop_back() {
		if (size() < 1)
			return;

		set(size() - 1, 0);

		if (offsetJ == 0) {
			offsetI--;
			offsetJ = chunkSize;
		} else {
			offsetJ--;
		}
		numElements--;
	}

	private void addChunk() {
		int[][] tmp = new int[data.length + 1][];
		for (int i = 0; i < data.length; i++) {
			tmp[i] = data[i];
		}
		tmp[tmp.length - 1] = new int[chunkSize];
		data = tmp;
	}

}
